﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Server.Manager
{
    class ModuleManager : Singleton<ModuleManager>
    {
        public event Action<BaseModule> ModuleLoaded;
        public event Action<BaseModule> ModuleUnloaded;

        readonly List<BaseModule> modules;

        readonly List<Action> Loads;
        readonly List<Action> Unloads;

        readonly Type ModuleType;

        public ModuleManager()
        {
            modules = new();
            ModuleType = typeof(BaseModule);
            Loads = new List<Action>();
            Unloads = new List<Action>();
        }

        public BaseModule[] GetAllModules()
        {
            return modules.ToArray();
        }

        public void Load()
        {
            foreach (var type in GetType().Assembly.GetTypes())
            {
                Type baseType = type.BaseType;
                while (baseType != null)
                {
                    if (baseType == ModuleType)
                    {
                        BaseModule module = Activator.CreateInstance(type, true) as BaseModule;
                        Loads.Insert(module.ModuleId, type.GetMethod("Load", BindingFlags.NonPublic | BindingFlags.Instance).CreateDelegate<Action>(module));
                        modules.Add(module);
                        break;
                    }
                    baseType = baseType.BaseType;
                }
            }

            foreach (var action in Loads)
            {
                action.Invoke();
            }
        }

        public void Unload()
        {

        }

        public void LoadMudule(string name)
        {

        }

        public void UnloadMudule(string name)
        {

        }
    }
}
